using System;
using System.Collections.Generic;
using Impact.Infrastructure.Plugins;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Impact.Infrastructure;
using Impact.Infrastructure.Exceptions;
using System.Text;
using System.Net.Mail;
using System.Web;
using System.Web.UI;

namespace Impact.Plugins
{
    /// <summary>
    /// Contact Us form plugin
    /// </summary>
    public class ContactPlugin : Impact.Infrastructure.Plugins.IImpactPlugin
    {

        private static Guid _id = new Guid( "75F16501-C96E-49cc-AD0D-DB8EA4D013CB" );
        private static Dictionary<string, PluginParameter> parameters;

        #region IImpactPlugin Members

        /// <summary>
        /// gets the unique ID of this plugin
        /// </summary>
        public Guid PluginId
        {
            get { return _id; }
        }

        /// <summary>
        /// gets the textual name of this plugin
        /// </summary>
        public string Name
        {
            get { return "Contact Us Form"; }
        }

        /// <summary>
        /// gets the list of parameters used by this plugin
        /// </summary>
        public Dictionary<string, PluginParameter> Parameters
        {
            get
            {
                if ( parameters == null )
                {
                    parameters = new Dictionary<string, PluginParameter>();
                    parameters.Add( "ShowFirstName", new PluginParameter( this, "ShowFirstName", typeof( bool ), false ) );
                    parameters.Add( "FirstNameRequired", new PluginParameter( this, "FirstNameRequired", typeof( bool ), false ) );
                    parameters.Add( "ShowLastName", new PluginParameter( this, "ShowLastName", typeof( bool ), false ) );
                    parameters.Add( "LastNameRequired", new PluginParameter( this, "LastNameRequired", typeof( bool ), false ) );
                    parameters.Add( "ShowEmail", new PluginParameter( this, "ShowEmail", typeof( bool ), false ) );
                    parameters.Add( "EmailRequired", new PluginParameter( this, "EmailRequired", typeof( bool ), false ) );
                    parameters.Add( "ShowPhone", new PluginParameter( this, "ShowPhone", typeof( bool ), false ) );
                    parameters.Add( "PhoneRequired", new PluginParameter( this, "PhoneRequired", typeof( bool ), false ) );
                    parameters.Add( "ShowComments", new PluginParameter( this, "ShowComments", typeof( bool ), false ) );
                    parameters.Add( "CommentsRequired", new PluginParameter( this, "CommentsRequired", typeof( bool ), false ) );

                    parameters.Add( "EmailToAddress", new PluginParameter( this, "Email To Address", typeof( string ), true ) );
                    parameters.Add( "EmailFromAddress", new PluginParameter( this, "Email From Address", typeof( string ), true ) );
                    parameters.Add( "EmailSubject", new PluginParameter( this, "Email Subject", typeof( string ), true ) );
                    parameters.Add( "ThankYouPage", new PluginParameter( this, "Thank You Page", typeof( string ), true ) );
                }
                return parameters;
            }
        }

        /// <summary>
        /// gets the admin interface for this plugin
        /// </summary>
        public IPluginAdmin Admin
        {
            get { return new ContactPluginAdmin(); }
        }

        /// <summary>
        /// Generates the controls inside "container" to display this plugin
        /// </summary>
        public void Render( Control container, Dictionary<string, PluginParameter> parameterValues )
        {

            HtmlTable table = new HtmlTable();
            HtmlTableRow row;
            HtmlTableCell cell;
            RequiredFieldValidator required;

            row = new HtmlTableRow();
            cell = new HtmlTableCell();
            cell.ColSpan = 4;
            cell.InnerHtml = "<span style=\"color: Red;\">*</span> Required Fields";
            row.Controls.Add( cell );
            table.Controls.Add( row );

            row = new HtmlTableRow();
            table.Controls.Add( row );

            if ( Utility.StringAsBool( parameterValues["ShowFirstName"].Value ) )
            {
                cell = new HtmlTableCell();
                cell.InnerText = "First Name";
                cell.Attributes.Add( "id", "firstnameLabel" );
                cell.Attributes.Add( "class", "label" );

                if ( Utility.StringAsBool( parameterValues["FirstNameRequired"].Value ) )
                {
                    required = new RequiredFieldValidator();
                    required.ControlToValidate = "firstname";
                    required.ErrorMessage = "*";
                    cell.Controls.Add( required );
                }
                row.Controls.Add( cell );

                cell = new HtmlTableCell();
                TextBox firstNameTextBox = new TextBox();
                firstNameTextBox.ID = "firstname";
                cell.Controls.Add( firstNameTextBox );
                row.Controls.Add( cell );
            }

            if ( Utility.StringAsBool( parameterValues["ShowEmail"].Value ) )
            {
                cell = new HtmlTableCell();
                cell.InnerHtml = "<span style=\"color: Red;\">*</span>Email";
                cell.Attributes.Add( "id", "emailLabel" );
                cell.Attributes.Add( "class", "label" );

                if ( Utility.StringAsBool( parameterValues["EmailRequired"].Value ) )
                {
                    required = new RequiredFieldValidator();
                    required.ControlToValidate = "email";
                    required.ErrorMessage = "";
                    cell.Controls.Add( required );
                }
                row.Controls.Add( cell );

                cell = new HtmlTableCell();
                TextBox emailTextBox = new TextBox();
                emailTextBox.ID = "email";
                cell.Controls.Add( emailTextBox );
                row.Controls.Add( cell );
            }

            row = new HtmlTableRow();
            table.Controls.Add( row );

            if ( Utility.StringAsBool( parameterValues["ShowLastName"].Value ) )
            {
                cell = new HtmlTableCell();
                cell.InnerText = "Last Name";
                cell.Attributes.Add( "id", "lastnameLabel" );
                cell.Attributes.Add( "class", "label" );

                if ( Utility.StringAsBool( parameterValues["LastNameRequired"].Value ) )
                {
                    required = new RequiredFieldValidator();
                    required.ControlToValidate = "lastname";
                    required.ErrorMessage = "*";
                    cell.Controls.Add( required );
                }
                row.Controls.Add( cell );

                cell = new HtmlTableCell();
                TextBox lastNameTextBox = new TextBox();
                lastNameTextBox.ID = "lastname";
                cell.Controls.Add( lastNameTextBox );
                row.Controls.Add( cell );
            }

            if ( Utility.StringAsBool( parameterValues["ShowPhone"].Value ) )
            {
                cell = new HtmlTableCell();
                cell.InnerText = "Telephone";
                cell.Attributes.Add( "id", "phoneLabel" );
                cell.Attributes.Add( "class", "label" );

                if ( Utility.StringAsBool( parameterValues["PhoneRequired"].Value ) )
                {
                    required = new RequiredFieldValidator();
                    required.ControlToValidate = "phone";
                    required.ErrorMessage = "*";
                    cell.Controls.Add( required );
                }
                row.Controls.Add( cell );

                cell = new HtmlTableCell();
                TextBox phoneTextBox = new TextBox();
                phoneTextBox.ID = "phone";
                cell.Controls.Add( phoneTextBox );
                row.Controls.Add( cell );
            }

            if ( Utility.StringAsBool( parameterValues["ShowComments"].Value ) )
            {
                row = new HtmlTableRow();
                cell = new HtmlTableCell();
                cell.InnerText = "Comments";
                cell.ColSpan = 4;
                cell.Attributes.Add( "id", "commentsLabel" );
                cell.Attributes.Add( "class", "label" );

                if ( Utility.StringAsBool( parameterValues["CommentsRequired"].Value ) )
                {
                    required = new RequiredFieldValidator();
                    required.ControlToValidate = "comments";
                    required.ErrorMessage = "*";
                    cell.Controls.Add( required );
                }
                row.Controls.Add( cell );
                table.Controls.Add( row );

                row = new HtmlTableRow();
                cell = new HtmlTableCell();
                cell.ColSpan = 4;
                TextBox commentsTextBox = new TextBox();
                commentsTextBox.ID = "comments";
                commentsTextBox.TextMode = TextBoxMode.MultiLine;
                commentsTextBox.Width = new Unit( 100, UnitType.Percentage );
                cell.Controls.Add( commentsTextBox );
                row.Controls.Add( cell );
                table.Controls.Add( row );
            }

            row = new HtmlTableRow();
            cell = new HtmlTableCell();
            cell.ColSpan = 4;
            cell.Attributes.Add( "id", "submitButton" );
            ImageButton submitButton = new ImageButton();
            submitButton.ID = "submit";
            //submitButton.Text = "Submit";
            submitButton.ImageUrl = "~/images/btn_submit.png";
            submitButton.Command += new CommandEventHandler( SubmitButton_Command );
            cell.Controls.Add( submitButton );
            row.Controls.Add( cell );
            table.Controls.Add( row );

            table.Attributes.Add( "id", "contact" );
            container.Controls.Add( table );

            _container = container;
            _values = parameterValues;
        }

        #endregion

        private void SubmitButton_Command( object sender, CommandEventArgs e )
        {
            Check.Require( _values, "Parameter Values have not been set" );

            TextBox firstname = (TextBox)Utility.FindControlRecursive( _container.Controls, "firstname" );
            TextBox lastname = (TextBox)Utility.FindControlRecursive( _container.Controls, "lastname" );
            TextBox email = (TextBox)Utility.FindControlRecursive( _container.Controls, "email" );
            TextBox phone = (TextBox)Utility.FindControlRecursive( _container.Controls, "phone" );
            TextBox comments = (TextBox)Utility.FindControlRecursive( _container.Controls, "comments" );

            StringBuilder body = new StringBuilder();
            body.AppendFormat( "Contact Form Submitted: {0}\r\n\r\n", DateTime.Now.ToString() );
            body.AppendFormat( "Name: {0} {1}\r\n", firstname.Text, lastname.Text );
            body.AppendFormat( "Email: {0}\r\n", email.Text );
            body.AppendFormat( "Telephone: {0}\r\n", phone.Text );
            body.AppendFormat( "Comments:\r\n{0}", comments.Text );

            MailMessage message = new MailMessage( _values["EmailFromAddress"].Value, _values["EmailToAddress"].Value,
                _values["EmailSubject"].Value, body.ToString() );

            SmtpClient smtpClient = new SmtpClient();
            smtpClient.Send( message );

            HttpContext.Current.Response.Redirect( _values["ThankYouPage"].Value );
        }

        private Control _container;
        private Dictionary<string, PluginParameter> _values;

    }
}
